package com.tensquare.user.controller;

import cn.hutool.core.util.StrUtil;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import com.tensquare.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzb
 * @version 1.0
 * @create 2020/12/22 21:41
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    @PostMapping
    public Result add(@RequestBody Admin admin){
        adminService.add(admin);
        return new Result(true, StatusCode.OK,"添加管理员成功！");
    }

    //管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //管理员登录
        Admin loginAdmin = adminService.login(admin);
        if (loginAdmin != null){
            //将登录信息放到token中
            String token = jwtUtil.createJwt(loginAdmin.getId(), loginAdmin.getLoginname(), "admin");
            //将token信息放到result中，便于后面复制token
            Map map = new HashMap();
            map.put("name",loginAdmin.getLoginname());
            map.put("token",token);
            return new Result(true,StatusCode.OK,"管理员登录成功",map);
        }
        return new Result(false,StatusCode.ERROR,"管理员登录失败");
    }

    //根据id删除管理员
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        //从请求作用域中得到值
        Claims claims = (Claims) request.getAttribute("claims");
        //判断是否有值
        if (claims != null){
            //得到用户的角色
            String role = (String) claims.get("role");
            //判断是否是管理员
            if (StrUtil.isNotBlank(role) && "admin".equals(role)){
                adminService.delete(adminId);
                return new Result(true,StatusCode.OK,"删除管理员成功！");
            }

        }
        return new Result(false,StatusCode.ERROR,"无权访问");
    }
}
